package routers

import (
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"redTeaHouse/entity"
	"redTeaHouse/model"
	"redTeaHouse/utils"
	"strconv"
	"time"
)

func InitRouter() {

	gin.SetMode(gin.ReleaseMode)
	router := gin.Default()

	router.GET("login", func(c *gin.Context) {
		loginService(c)
	})
	router.GET("sendvertificationcode", func(c *gin.Context) {
		sendVertificationCodeService(c)
	})
	router.GET("register", func(c *gin.Context) {
		registerService(c)
	})
	router.GET("judgevertifycode", func(c *gin.Context) {
		judgeVertifycode(c)
	})
	router.GET("randomStory", func(context *gin.Context) {
		randomStory(context)
	})
	router.GET("uploadStory", func(context *gin.Context) {
		uploadStory(context)
	})
	/*
		TODO：重置密码
	*/

	go utils.DeleteOutTimeVertifyCode()
	router.Run(":8080")
}

func loginService(c *gin.Context) {
	LogInSuccess := 1
	LogInFail := 0
	phone := c.Query("phone")
	password := c.Query("password")
	status := vertifyPassword(phone, password)
	defaultNickname := "NN:车泰甫yyds"
	defaultAutography := "AG:有志者事竟成"
	/*
		TODO:用户的数据，昵称，签名什么的应该是存在服务器上，不过手机端还没有设置的功能，所以先弄成默认的。
	*/
	if status == 0 {
		c.JSON(http.StatusOK, strconv.Itoa(LogInSuccess)+defaultNickname+defaultAutography)
	} else {
		c.JSON(http.StatusOK, strconv.Itoa(LogInFail))
	}
}
func vertifyPassword(phone string, password string) int {
	var passwordFromDatabase string
	DB := utils.OpenDatabase()
	rowObj := DB.QueryRow("select password from user where phone=?", phone)
	rowObj.Scan(&passwordFromDatabase)
	if passwordFromDatabase == password {
		return 0
	}
	return 1
}

func sendVertificationCodeService(c *gin.Context) {
	var stringVertifyCode string
	vertifydbName := "vertifycode"
	phoneExisted := "0"
	phone := c.Query("phone")
	if model.FindExistPhone(phone, vertifydbName) {
		c.JSON(http.StatusOK, phoneExisted)
	} else {
		vertifyCode := []int{}
		vertifyCode = append(vertifyCode, getRandomNumber(0), getRandomNumber(100), getRandomNumber(200), getRandomNumber(300))
		for _, i := range vertifyCode {
			stringI := strconv.Itoa(i)
			stringVertifyCode += stringI
		}
		saveVertifyCode(stringVertifyCode, phone)
		c.JSON(http.StatusOK, stringVertifyCode)
	}
}
func getRandomNumber(NumToDistinguishRandomNumbers int64) int {
	rand.Seed(time.Now().UnixNano() + NumToDistinguishRandomNumbers)
	return rand.Intn(10)
}
func saveVertifyCode(vertifyCode string, phone string) {
	DB := utils.OpenDatabase()
	defer DB.Close()
	_, err := DB.Exec("insert into vertifycode(vertifycode,time,phone) value (?,?,?)", vertifyCode, time.Now().Format("15:04:05"), phone)
	if err != nil {
		panic(err)
	}
}

func judgeVertifycode(c *gin.Context) {
	var savedPhone string
	acceptedVertifyCode := c.Query("vertifycode")
	phone := c.Query("phone")
	DB := utils.OpenDatabase()
	defer DB.Close()
	res := DB.QueryRow("select phone from vertifycode where vertifycode=?", acceptedVertifyCode)
	res.Scan(&savedPhone)
	if savedPhone == phone {
		c.JSON(http.StatusOK, true)
	} else {
		c.JSON(http.StatusOK, false)
	}
}

func registerService(c *gin.Context) {
	RegisterSuccess := 1
	RegisterFail := 0
	RegisterFailForPhoneExisted := -1
	phone := c.Query("phone")
	password := c.Query("password")
	if model.FindExistPhone(phone, "user") {
		c.JSON(http.StatusOK, RegisterFailForPhoneExisted)
	} else {
		DB := utils.OpenDatabase()
		defer DB.Close()

		_, err := DB.Exec("insert into user(phone,password) value (?,?)", phone, password)
		if err != nil {
			c.JSON(http.StatusOK, RegisterFail)
			panic(err)
		}
		c.JSON(http.StatusOK, RegisterSuccess)
	}
}

func randomStory(context *gin.Context) {
	DB := utils.OpenDatabase()
	defer DB.Close()

	var maxId int
	res := DB.QueryRow("select MAX(id) from story ")
	res.Scan(&maxId)

	var randomId int
	var story entity.Story
	randomId = getRandomNumber(0) % maxId
	if randomId == 0 {
		randomId = maxId //等于0实际就是余完，即取最后一个
	}
	rowObj := DB.QueryRow("select * from story where id=?", randomId)
	rowObj.Scan(&story.Id, &story.Title, &story.Content, &story.Time, &story.Custom_tag, &story.Tag, &story.State, &story.Author)
	context.JSON(http.StatusOK, story)
}

func uploadStory(context *gin.Context) {
	DB := utils.OpenDatabase()
	defer DB.Close()

	var story entity.Story
	story.Title = context.Query("title")
	story.Tag, _ = strconv.Atoi(context.Query("tag"))
	story.Time = context.Query("time")
	story.State = context.Query("state")
	story.Author = context.Query("author")
	story.Custom_tag = context.Query("custom_tag")
	story.Content = context.Query("content")

	_, err := DB.Exec("insert into story( title, content, time, custom_tag, tag, state, author) value (?,?,?,?,?,?,?)", story.Title, story.Content, story.Time, story.Custom_tag, story.Tag, story.State, story.Author)
	if err != nil {
		panic(err)
	}

}
